/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package be.free.ts.infrastructure;

import com.google.inject.AbstractModule;
import com.google.inject.Provider;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;

import javax.inject.Singleton;
import javax.persistence.EntityManager;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Set;

/**
 * Module to bind the Repository interfaces with the Spring Data framework.
 *
 * @author Christophe De Blende
 * @since 08/12/12
 */
public class RepositoryModule extends AbstractModule {

	protected void configure() {
		requireBinding(EntityManager.class);
		setupRepositories();
	}

	private void setupRepositories() {
		Reflections reflections = new Reflections(new ConfigurationBuilder()
				.setUrls(ClasspathHelper.forPackage("be.free.ts"))
				.setScanners(new SubTypesScanner()));

		Set<Class<? extends JpaRepository>> jpaRepositories = reflections.getSubTypesOf(JpaRepository.class);
		for (Class<? extends JpaRepository> repository : jpaRepositories) {
			if (repository.isInterface()) {
				bind(repository)
						.toProvider(new JpaRepositoryProvider(repository, getProvider(EntityManager.class)));
			}
		}
	}

	private class JpaRepositoryProvider<R extends JpaRepository> implements Provider<R> {

		private final Class<R> repositoryType;

		private final Provider<EntityManager> entityManager;

		public JpaRepositoryProvider(Class<R> repositoryType, Provider<EntityManager> entityManager) {
			this.repositoryType = repositoryType;
			this.entityManager = entityManager;
		}

		@Override
		@Singleton
		public R get() {
			EntityManager entityManagerProxy = (EntityManager) Proxy.newProxyInstance(this.getClass().getClassLoader(),
					new Class[]{EntityManager.class},
					new EntityManagerInterceptor(entityManager));
			return new JpaRepositoryFactory(entityManagerProxy).getRepository(repositoryType);
		}
	}

	private class EntityManagerInterceptor implements InvocationHandler {

		private final Provider<EntityManager> entityManager;

		private EntityManagerInterceptor(Provider<EntityManager> entityManager) {
			this.entityManager = entityManager;
		}

		@Override
		public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
			return method.invoke(entityManager.get(), objects);
		}
	}

}
